package diploma.kisel.modelas.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import diploma.kisel.hibernate.util.HibernateUtil;
import diploma.kisel.modelas.domain.Device;
import diploma.kisel.modelas.domain.Project;
import diploma.kisel.modelas.domain.User;
import diploma.kisel.modelas.repository.api.ProjectRepository;

public class ProjectRepositoryImpl implements ProjectRepository{

	EntityManager em = HibernateUtil.getEm();
	
	@Override
	public List<Project> findAll() {
		List<Project> projects = em.createNamedQuery("Project.findAll",
				Project.class).getResultList();
		return projects;
	}

	@Override
	public Project findById(int id) {
		TypedQuery<Project> query= em.createNamedQuery("Project.findById", Project.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@Override
	public Project save(Project project) {
		em.getTransaction().begin();
		em.persist(project);
		em.getTransaction().commit();
		return project;
	}

	@Override
	public Project update(Project project) {
		em.getTransaction().begin();
		em.merge(project);
		em.getTransaction().commit();
		return project;
	}

	@Override
	public void remove(Project project) {
		em.getTransaction().begin();
		em.remove(project);
		em.getTransaction().commit();		
	}

	@Override
	public List<Project> findByUser(User user) {
		TypedQuery<Project> query= em.createNamedQuery("Project.findByUser", Project.class);
		query.setParameter("user", user);
		return query.getResultList();
	}

}
